package com.cndw.kungfu.model.activity;

import java.text.ParseException;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.cndw.kungfu.config.ConstantsModel;
import com.cndw.kungfu.dao.QuizDao;
import com.cndw.kungfu.domain.QuizQuestion;
import com.cndw.kungfu.ext.TimeProcesser;
import com.cndw.kungfu.model.Context;

@Component
public class QuizManager {
	@Autowired
	private QuizDao quizDao;
	
	public  List<QuizQuestion> getQuestion(){
		try{
		return quizDao.getQuestions();
		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 处理回答结果
	 * @param quiz
	 * @param rightAnswer
	 */
	public void dealResult(Quiz quiz, boolean rightAnswer){
		if(rightAnswer){
			quiz.setRightCount(quiz.getRightCount() + 1);
		}else{
			quiz.setWrongCount(quiz.getWrongCount() + 1);
		}
		quiz.setLastQueReply(true);
	}
	
	/**
	 * 清除quiz缓存
	 * @param playerId
	 * @param quiz
	 * @return 是否完成本次测试
	 */
	public boolean finishQuiz(long playerId, Quiz quiz){
		if(quiz.getRightCount() + quiz.getWrongCount() >= ConstantsModel.quizQuestionNumLimit){
			Context.getDataServer().getQuizmap().remove(playerId);
			return true;
		}else{
			return false;
		}
	}
	
	/**
	 * 获取答题轮次
	 * @param type
	 * @return
	 */
	public int getQuizRound(int type){
		//日常答题
		if(type == 0){
			for(int i = 0; i < ConstantsModel.quizNormalRound; i++){
				int time[] = ConstantsModel.quizTime[i];
				if(TimeProcesser.inTimePeriod(time[0], time[1])){
					return i + 1;
				}
			}
		}else if(type == 1){//灯谜活动
			int curTime = TimeProcesser.getUnixTime();
			boolean activityTime = false;
			try {
				activityTime = curTime > TimeProcesser.getUnixTimeByString(ConstantsModel.quizActivityBeginTime) && curTime < TimeProcesser.getUnixTimeByString(ConstantsModel.quizActivityEndTime);
			} catch (ParseException e) {
				e.printStackTrace();
			} 
			for(int i = ConstantsModel.quizNormalRound; activityTime && i < ConstantsModel.quizTime.length; i++){
				int time[] = ConstantsModel.quizTime[i];
				if(TimeProcesser.inTimePeriod(time[0], time[1])){
					return i + 1;
				}
			}
		}
		return 0;
	}
}
